<template>
    <view>
        <view class="userInfo  ">
            <view class="bg-white flex xxl bold user-info-container p-30 m-b-40">
                <view class="avatar-container">
                    <u-avatar :src="userInfo.avatarUrl" size="large"></u-avatar>
                    <view class="edit-avatar-icon">
                        <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="avatar-button">
                            <uni-icons type="compose" size="18" color="#666"></uni-icons>
                        </button>
                    </view>
                </view>
                <view class="m-l-40 m-t-20 nickname-container">
                    <view class="nickname-display-container">
                        <text class="nickname-text">{{ userInfo.nickName || '未设置昵称' }}</text>
                        <view class="edit-icon" @click="openNicknameDialog">
                            <uni-icons type="compose" size="18" color="#666"></uni-icons>
                        </view>
                    </view>
                </view>
            </view>
            <!-- <image src="https://www.enjoyluxe.cn/api/files/weixin/img/mine-bg.jpg" mode="" class="mine-bg">
            </image> -->
        </view>

        <view class="">

        </view>
        <view class="list">
            <u-cell-group>
                <u-cell-item title="历史溯源纪录" arrow-direction="left" value="历史查询" @click="goPages('list')">
                    <template v-slot:icon>
                        <image src="/static/list.png" mode="" class="cell-icon"></image>
                    </template>
                </u-cell-item>
                <u-cell-item title="意见反馈" arrow-direction="left" value="反馈" @click="goPages('opinion')">
                    <template v-slot:icon>
                        <image src="/static/opinion.png" mode="" class="cell-icon"></image>
                    </template>
                </u-cell-item>
                <u-cell-item title="关于我们" arrow-direction="left" value="当前版本V1.0.0" @click="goPages('about')">
                    <template v-slot:icon>
                        <image src="/static/about.png" mode="" class="cell-icon"></image>
                    </template>
                </u-cell-item>
            </u-cell-group>
        </view>
        <view class="m-t-30 ">
            <button v-if="token" class="status_red bg-white outLogin" @click="outLogin">退出登录</button>
            <button v-else class="status_success bg-white outLogin" @click="login">登录</button>
        </view>
        <!-- 昵称修改弹窗 -->
        <u-popup v-model="showNicknameDialog" mode="center" width="80%" height="auto">
            <view class="nickname-dialog">
                <view class="dialog-title">修改昵称</view>
                <view class="dialog-content">
                    <input type="nickname" v-model="newNickname" placeholder="请输入新昵称" @change="onNicknameChange"
                        class="nickname-input" />
                </view>
                <view class="dialog-footer">
                    <button class="dialog-btn cancel-btn" @click="showNicknameDialog = false">取消</button>
                    <button class="dialog-btn confirm-btn" @click="updateNickname">确认</button>
                </view>
            </view>
        </u-popup>

    </view>
</template>

<script setup>
    import {
        ref,
        reactive
    } from 'vue'
    import {
        onLoad
    } from '@dcloudio/uni-app'
    import {
        apiUpdateUserInfo
    } from "@/api/index.js"



    const userInfo = ref({})
    const showNicknameDialog = ref(false)
    const showOutLogin = ref(false)
    const newNickname = ref('')
    const token = ref('')

    /**
     * 处理微信昵称输入变化事件
     * @param {Object} e - 事件对象，包含用户输入的昵称
     */
    const onNicknameChange = (e) => {
        // 获取输入的昵称
        const nickname = e.detail.value
        // 更新昵称值
        newNickname.value = nickname
    }

    const goPages = (type) => {
        let url = '/pages/list/list'
        if (type == 'about') {
            url = '/pages/about/about'
        } else if (type == 'opinion') {
            url = '/pages/opinion/opinion'
        }

        uni.navigateTo({
            url: url
        })
    }

    /**
     * 退出登录方法
     * 清除本地存储的用户信息并跳转到登录页面
     */
    const outLogin = () => {
        uni.showModal({
            title: '提示',
            content: '是否确认退出登录',
            success: function(res) {
                if (res.confirm) {
                    uni.removeStorageSync('token')
                    uni.removeStorageSync('userInfo')
                    uni.$u.toast('您已退出登录')
                    setTimeout(() => {
                        uni.reLaunch({
                            url: '/pages/user/user'
                        })
                    }, 800)
                } else if (res.cancel) {
                    console.log('用户点击取消');
                }
            }
        });
    }


    //登录
    const login = () => {
        uni.reLaunch({
            url: '/pages/login/login'
        })
    }

    const changeBase64 = (url, type) => {
        type = url.split('.').pop();
        return new Promise((resolve, reject) => {
            uni.getFileSystemManager().readFile({
                filePath: url, //选择图片返回的相对路径
                encoding: 'base64', //编码格式
                success: res => {
                    resolve('data:image/' + type.toLocaleLowerCase() + ';base64,' + res.data)
                    resolve(res.data)
                },
                fail: res => {
                    reject(res.errMsg)
                }
            })
        })
    }


    /**
     * 处理微信头像选择事件
     * @param {Object} e - 事件对象，包含用户选择的头像临时路径
     */
    const onChooseAvatar = async (e) => {
        let tempFilePath = await changeBase64(e.detail.avatarUrl)

        //更新数据库
        try {
            let res = await apiUpdateUserInfo({
                id: userInfo.value.id,
                avatarUrl: tempFilePath
            })
        } catch (err) {
            console.log(err);
        }

        // 更新用户信息
        userInfo.value.avatarUrl = tempFilePath

        // 更新本地存储
        uni.setStorageSync('userInfo', userInfo.value)

        // 显示成功提示
        uni.showToast({
            title: '头像修改成功',
            icon: 'success'
        })
    }

    /**
     * 更新用户昵称
     * 从弹窗中获取新昵称并更新到用户信息中
     */
    const updateNickname = async () => {
        if (newNickname.value && newNickname.value !== userInfo.value.nickName) {
            // 更新用户信息
            userInfo.value.nickName = newNickname.value
            //更新数据库
            try {
                let res = await apiUpdateUserInfo({
                    id: userInfo.value.id,
                    nickName: newNickname.value
                })
            } catch (err) {
                console.log(err);
            }


            // 更新本地存储
            uni.setStorageSync('userInfo', userInfo.value)

            // 显示成功提示
            uni.showToast({
                title: '昵称修改成功',
                icon: 'success'
            })

            // 关闭弹窗
            showNicknameDialog.value = false
        } else if (!newNickname.value) {
            uni.showToast({
                title: '昵称不能为空',
                icon: 'none'
            })
        } else {
            // 关闭弹窗
            showNicknameDialog.value = false
        }
    }

    /**
     * 打开昵称修改弹窗
     * 预填充当前用户昵称到输入框中
     */
    const openNicknameDialog = () => {
        // 预填充当前昵称
        newNickname.value = userInfo.value.nickName || ''
        // 打开弹窗
        showNicknameDialog.value = true
    }

    onLoad(() => {
        userInfo.value = uni.getStorageSync('userInfo')
        token.value = uni.getStorageSync('token')
    })
</script>

<style lang="scss" scoped>
    .userInfo {
        // padding: 0 40rpx;
        // padding-bottom: 40rpx;
    }

    .mine-bg {
        width: 100%;
        height: 186rpx;
    }

    .cell-icon {
        width: 46rpx;
        height: 46rpx;
        margin-right: 20rpx;
    }

    .outLogin {
        padding: 10rpx 0;
    }

    .user-info-container {
        position: relative;
    }

    .avatar-container {
        position: relative;
    }

    .nickname-container {
        display: flex;
        align-items: center;
    }

    .edit-icon {
        margin-left: 10rpx;
        display: flex;
        align-items: center;
        background-color: rgba(255, 255, 255, 0.8);
        border-radius: 50%;
        width: 36rpx;
        height: 36rpx;
        justify-content: center;
    }

    .edit-avatar-icon {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 36rpx;
        height: 36rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .avatar-button {
        background-color: rgba(255, 255, 255, 0.8);
        border-radius: 50%;
        width: 36rpx;
        height: 36rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;
        margin: 0;
        line-height: 1;
        border: none;
    }

    .nickname-display-container {
        display: flex;
        align-items: center;
        background-color: rgba(255, 255, 255, 0.8);
        border-radius: 8rpx;
        padding: 6rpx 12rpx;
    }

    .nickname-text {
        font-size: 28rpx;
        width: 200rpx;
    }

    .nickname-dialog {
        padding: 30rpx;
        background-color: #fff;
        border-radius: 12rpx;
    }

    .dialog-title {
        font-size: 32rpx;
        font-weight: bold;
        text-align: center;
        margin-bottom: 30rpx;
    }

    .dialog-content {
        margin-bottom: 30rpx;
    }

    .nickname-input {
        width: 100%;
        height: 80rpx;
        border: 1px solid #eee;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        box-sizing: border-box;
    }

    .dialog-footer {
        display: flex;
        justify-content: space-between;
    }

    .dialog-btn {
        width: 45%;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        border-radius: 8rpx;
        font-size: 28rpx;
    }

    .cancel-btn {
        background-color: #f2f2f2;
        color: #666;
    }

    .confirm-btn {
        background-color: #007aff;
        color: #fff;
    }
</style>